<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (fangjin_enterlo) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function getip(){
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if(!empty($_SERVER["REMOTE_ADDR"])){
        $cip = $_SERVER["REMOTE_ADDR"];
    }
    else{
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);
    return($cip);
}
//加密函数
function encrypt($txt, $key = ''){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="Mlwc3.*5.FlNrPJLhPYzyQPHtN8aB*o9V";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode(time().'_'.$txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}
//解密函数
function decrypt($txt, $key = '', $ttl = 0){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(MD5_KEY);
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="Mlwc3.*5.FlNrPJLhPYzyQPHtN8aB*o9V";
    $knum = 0;$i = 0;
    $tlen = @strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1);
    $txt = @substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars,$ch2);
    $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars,$ch3);
    $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    $tmp = trim(base64_decode($tmp));
    if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
        if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
            $tmp = null;
        }else{
            $tmp = substr($tmp,11);
        }
    }
    return $tmp;
}

//电话号码判断
function isTelephone($data){
    return (preg_match("/^1[345789]{1}\d{9}$/",$data))?true:false;
}
function checkTel($data){
    if (!$data)
        return [
            'message' => '手机号码不能为空'
        ];
    if (!isTelephone($data))
        return [
            'message' => '手机号码不正确'
        ];
    return true;
}

//座机号码判断
function isMob($data){
    return (preg_match("/^([0-9]{3,4}-)[0-9]{7,8}$/",$data)?true:false);
}

function genRandomString($len = 15) {
    $chars = array(
        "a", "b", "fangjin_enterlo", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9",'-','_','.'
    );
    $charsLen = count($chars) - 1;
    // 将数组打乱
    shuffle($chars);
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function dataSign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}


/**
 * @param $html
 * @return mixed|string
 * 补全标签
 */
function CloseTags($html)
{
    // strip fraction of open or close tag from end (e.g. if we take first x characters, we might cut off a tag at the end!)
    $html = preg_replace('/<[^>]*$/','',$html); // ending with fraction of open tag
    // put open tags into an array
    preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $opentags = $result[1];
    // put all closed tags into an array
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closetags = $result[1];
    $len_opened = count($opentags);
    // if all tags are closed, we can return
    if (count($closetags) == $len_opened) {
        return $html;
    }
    // close tags in reverse order that they were opened
    $opentags = array_reverse($opentags);
    // self closing tags
    $sc = array('br','input','img','hr','meta','link');
    // ,'frame','iframe','param','area','base','basefont','col'
    // should not skip tags that can have content inside!
    for ($i=0; $i < $len_opened; $i++)
    {
        $ot = strtolower($opentags[$i]);
        if (!in_array($opentags[$i], $closetags) && !in_array($ot,$sc))
        {
            $html .= '</'.$opentags[$i].'>';
        }
        else
        {
            unset($closetags[array_search($opentags[$i], $closetags)]);
        }
    }
    return $html;
}


function showDate($data){
    return date('Y-m-d H:i:s',$data);
}
function showYDate($data){
    if ($data == '')
        return false;
    return date('Y-m-d',$data);
}

function showJSDate($data){
    $date = date('Y-m-d H:i:s',$data);
    return str_replace(' ','T',$date);
}

function encryptTel($data){
    return substr_replace($data,'****',3,4);
}

function encryptName($data,$sex){
    return mb_substr($data,0,1,"utf-8").$sex;
}

function showStyle($data){
    $zhuZhai = ['普通住宅','洋房','别墅','两限房','经济适用房'];
    $shangPu = ['写字楼','商铺'];
    if (in_array($data,$zhuZhai)){
        return '住宅';
    }
    elseif (in_array($data,$shangPu)){
        return '商业类';
    }
    else{
        return '住宅';
    }
}

function showContent($data){
    return htmlspecialchars_decode($data);
}

function GetIpLookup($ip = ''){
    if(empty($ip))
        $ip = getip();
    $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$ip}";
    $ret = https_request($url);
    $arr = json_decode($ret,true);
    $arr['province'] = $arr['region'];
    return $arr;
}
function https_request($url,$data = null){
    $curl = curl_init();

    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);

    if(!empty($data)){//如果有数据传入数据
        curl_setopt($curl,CURLOPT_POST,1);//CURLOPT_POST 模拟post请求
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//传入数据
    }

    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    $output = curl_exec($curl);
    curl_close($curl);

    return $output;
}

function showBuildingPoint($info){
    $arr = explode(',',$info['transfer_point_1']);
    $info['transfer_point_1'] = $arr[0];
    $info['transfer_point_1_rate'] = $arr[1];
    $arr = explode(',',$info['agency_point_1']);
    $info['agency_point_1'] = $arr[0];
    $info['agency_point_1_rate'] = $arr[1];
    $arr = explode(',',$info['agency_point_2']);
    $info['agency_point_2'] = $arr[0];
    $info['agency_point_2_rate'] = $arr[1];
    $arr = explode(',',$info['agency_point_3']);
    $info['agency_point_3'] = $arr[0];
    $info['agency_point_3_rate'] = $arr[1];
    $arr = explode(',',$info['agency_point_4']);
    $info['agency_point_4'] = $arr[0];
    $info['agency_point_4_rate'] = $arr[1];
    $arr = explode(',',$info['source_point_1']);
    $info['source_point_1'] = $arr[0];
    $info['source_point_1_rate'] = $arr[1];
    $arr = explode(',',$info['source_point_2']);
    $info['source_point_2'] = $arr[0];
    $info['source_point_2_rate'] = $arr[1];
    $arr = explode(',',$info['source_point_agent']);
    $info['source_point_agent'] = $arr[0];
    $info['source_point_agent_rate'] = $arr[1];
    $arr = explode(',',$info['source_point_service']);
    $info['source_point_service'] = $arr[0];
    $info['source_point_service_rate'] = $arr[1];
    $arr = explode(',',$info['source_point_expand']);
    $info['source_point_expand'] = $arr[0];
    $info['source_point_expand_rate'] = $arr[1];
    return $info;
}

function plainText($params){
    $content_02 = htmlspecialchars_decode($params);//把一些预定义的 HTML 实体转换为字符
    $content_03 = str_replace("&nbsp;","",$content_02);//将空格替换成空
    $contents = strip_tags($content_03);//函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
//    $con = mb_substr($contents, 0, 100,"utf-8");//返回字符串中的前100字符串长度的字符
    return  $contents;
}


/**
 *      把秒数转换为时分秒的格式
 *      @param Int $times 时间，单位 秒
 *      @return String
 */
function secToTime($time)
{
    $d = floor($time / (3600*24));
    $h = floor(($time % (3600*24)) / 3600);
    $m = floor((($time % (3600*24)) % 3600) / 60);
    if($d>'0'){
        return $d.'天'.$h.'小时'.$m.'分';
    }else{
        if($h!='0'){
            return $h.'小时'.$m.'分';
        }else{
            return $m.'分';
        }
    }
}

function showMobImg($img){
    return str_replace(basename($img),'thumb_'.basename($img),$img);
}

function showBackImg($img){
    return str_replace("\\",'/',$img);
}


